import os.path
import re
import subprocess
from shutil import copyfile

from BladeFerm.Lib.Common import logger


# 递归函数


def copy_file(path_read, path_write, skip_dir='pycache'):
    """
    复制文件到目标路径
    Args:
        path_read:
        path_write:
        skip_dir:

    Returns:

    """
    logger.info(f'ReadPath: {path_read}')
    logger.info(f'WritePath: {path_write}')
    names = os.listdir(path_read)
    for name in names:
        path_read_new = path_read + "\\" + name
        path_write_new = path_write + "\\" + name
        if os.path.isdir(path_read_new):
            if not os.path.exists(path_write_new):
                os.mkdir(path_write_new)
            copy_file(path_read_new, path_write_new)
        else:
            if re.search(skip_dir, path_read_new, re.I):
                logger.info(f'Skip file: {path_read_new}')
            else:
                if not os.path.exists(path_write_new):
                    copyfile(path_read_new, path_write_new)
                    logger.info(f'copy file: {path_read_new}')


def act_package(work_dir='./venv_site-packages'):
    """
    执行打包操作
    Returns:

    """
    os.chdir(work_dir)
    bat_cmd = 'C:\qturbo-python\Python36-32\python setup.py sdist bdist_wheel'
    logger.info(f'执行目录：{os.getcwd()}')
    logger.info(f'打包命令：{bat_cmd}')
    p = subprocess.Popen(bat_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    p.communicate(timeout=1200)
    status = p.returncode
    os.chdir('..')
    logger.info(f'status: {status}')


if __name__ == '__main__':
    hui_blade_frame = './BladeFerm'
    target_bf = 'E:\Web_AutoTest\Project\\venv_site-packages\BladeFerm'
    # 拷贝到目标目录下
    # clear_dir(target_bf)
    copy_file(hui_blade_frame, target_bf)

    # 打包命令
    work_dir = 'E:\Web_AutoTest\Project\\venv_site-packages'
    act_package(work_dir)

